import { dayjs } from 'element-plus';
import { initMultipleData } from '@/utils';
import userStore from '@/store/modules/user';
import { isHttp } from '@/utils/validate';

// 默认值
export const DEFAULT_TEXT = '-';

// 格式化时间
export const FORMAT_DATE = (date, type = 'YYYY-MM-DD HH:mm') => {
  if (!date) return DEFAULT_TEXT;
  return dayjs(date).format(type);
};

// 初始化得到的开始时间和结束时间
function initDate(date, type) {
  if (type === 'start') {
    return dayjs(date).startOf('day').format('YYYY-MM-DD HH:mm:ss');
  }
  if (type === 'end') {
    return dayjs(date).endOf('day').format('YYYY-MM-DD HH:mm:ss');
  }
}
// 时间快捷选项
export const DATE_CUTS = {
  // 最近7天
  LAST_7_DAYS() {
    const end = dayjs();
    const start = end.subtract(6, 'day');
    return [initDate(start, 'start'), initDate(end, 'end')];
  },
  // 最近31天
  LAST_31_DAYS() {
    const end = dayjs();
    const start = end.subtract(30, 'day');
    return [initDate(start, 'start'), initDate(end, 'end')];
  },
  // 最近180天
  LAST_180_DAYS() {
    const end = dayjs();
    const start = end.subtract(179, 'day');
    return [initDate(start, 'start'), initDate(end, 'end')];
  },
  // 本周
  THIS_WEEK() {
    const end = dayjs().endOf('week');
    const start = end.startOf('week');
    return [initDate(start, 'start'), initDate(end, 'end')];
  },
  // 上周
  PREV_WEEK() {
    const end = dayjs().startOf('week').subtract(1, 'day');
    const start = end.startOf('week');
    return [initDate(start, 'start'), initDate(end, 'end')];
  },
  // 本月
  THIS_MONTH() {
    const end = dayjs().endOf('month');
    const start = end.startOf('month');
    return [initDate(start, 'start'), initDate(end, 'end')];
  },
  // 上月
  PREV_MONTH() {
    const end = dayjs().startOf('month').subtract(1, 'day');
    const start = end.startOf('month');
    return [initDate(start, 'start'), initDate(end, 'end')];
  }
};

// 站点类型下拉 和后台约定的值，但从后台拉取
// export const SITE_TYPE_LIST = reactive([
// { label: '自建站', value: 1 },
// { label: 'obs站', value: 2 },
// { label: 'lms站', value: 3 },
// { label: 'wp站', value: 4 },
// { label: '店匠', value: 5 },
// { label: 'shopify', value: 6 },
// { label: 'clickfunnels', value: 7 },
// { label: 'shopline', value: 8 },
// { label: 'funnelish', value: 9 }
// ]);

// 该站点类型value下，域名邮箱需要显示
export const DOMAIN_EMAILS_VALUES = [1, 2, 3, 4];
// 该站点类型value下，登录邮箱需要显示
export const LOGIN_EMAILS_VALUES = [5, 6, 7, 8, 9];
// 该站点类型value下，邮箱模板logo需要显示
export const EMAIL_LOGO_VALUES = [1, 2, 4];
// 分页参数
export const PAGES = () => {
  return { page: 1, per_page: 20 };
};

// 申请状态
export const APPLY_STATUS_LIST = [
  { label: '待处理', value: 1 },
  { label: '处理中', value: 3 },
  { label: '已完成', value: 4 },
  { label: '已驳回', value: 2 },
  { label: '已取消', value: 5 }
];

// 下拉-多选公共属性
export const SELECT_MULTIPLE_ATTRS = (form, key, allValue) => {
  return {
    multiple: true,
    collapseTags: true,
    collapseTagsTooltip: true,
    class() {
      return form[key]?.length === 1 && form[key]?.[0] === allValue
        ? 'tag-not-delete'
        : undefined;
    },
    change() {
      initMultipleData(form, key, allValue);
    }
  };
};

// 级联-多选公共属性
export const CASCADER_MULTIPLE_ATTRS = (form, key, allValue) => {
  return {
    showAllLevels: false,
    collapseTags: true,
    collapseTagsTooltip: true,
    props: {
      emitPath: false,
      multiple: true,
      label: 'name',
      value: 'id',
      children: 'childs'
    },
    size() {
      return form[key]?.length ? 'small' : undefined;
    },
    class() {
      return form[key]?.length === 1 && form[key]?.[0] === allValue
        ? 'tag-not-delete'
        : undefined;
    },
    change() {
      initMultipleData(form, key, allValue);
    }
  };
};

// 通过unique_id获取该对象
export const GET_OBJ_BUY_UNIQUEID = (list, unique_id) => {
  list = list || [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.unique_id === unique_id) return item;
    if (item.childs?.length) {
      const obj = GET_OBJ_BUY_UNIQUEID(item.childs, unique_id);
      if (obj) return obj;
    }
  }
};

// 用过可见公司ids拿到不可见公司ids
export const HIDDEN_COMPANY_IDS = visible_companies => {
  visible_companies = visible_companies || [];
  const companyMap = userStore().companyMap || {};
  const hiddenIds = [];
  Object.keys(companyMap).forEach(id => {
    id = Number(id);
    if (!visible_companies.includes(id)) hiddenIds.push(id);
  });
  return hiddenIds;
};

// 用过不可见公司ids拿到可见公司ids
export const VISIBLE_COMPANY_IDS = hidden_companyies => {
  hidden_companyies = hidden_companyies || [];
  const companyMap = userStore().companyMap || {};
  const visibleIds = [];
  Object.keys(companyMap).forEach(id => {
    id = Number(id);
    if (!hidden_companyies.includes(id)) visibleIds.push(id);
  });
  return visibleIds;
};

// 通过公司id数组拿到公司name数组
export const COMPANY_NAME = ids => {
  ids = ids || [];
  const names = [];
  const companyMap = userStore().companyMap || {};
  ids.forEach(id => {
    names.push(companyMap[id]?.label);
  });
  return names;
};

// 处理团队和公司查询参数
export const INIT_ORANIZE_PARAMS = (form, activeOranize) => {
  const _activeOranize = activeOranize;
  form.group_id = _activeOranize.id;
  // if (_activeOranize.is_company) {
  //   delete form.group_id;
  //   form.company_id = _activeOranize.id;
  // } else {
  //   delete form.company_id;
  //   form.group_id = _activeOranize.id;
  // }
};

// 处理查询时间
export function INIT_SEARCH_TIME(form, timeList, startCode, endCode) {
  if (timeList?.length === 2) {
    form[startCode] = dayjs(timeList[0]).toISOString();
    form[endCode] = dayjs(timeList[1]).toISOString();
  } else {
    form[startCode] = undefined;
    form[endCode] = undefined;
  }
}

// 获取图片显示地址
export const IMG_URL = url => {
  if (!url) return undefined;
  if (isHttp(url)) return url;
  // const baseUrl = 'https://oms.test.thierex.com';
  const baseUrl = location.origin;
  return baseUrl + `/common/store/download${url}`;
};

// 获取文件地址
export const FILE_URL = url => {
  if (!url) return undefined;
  // const baseUrl = 'http://172.18.2.75:8080';
  return `/common/store/download${url}`;
};

// 通过名字模糊搜索用户id
export const GET_USER_IDS = name => {
  if (!name) return [];
  const _userMap = userStore().userMap;
  const list = [];
  Object.keys(_userMap).forEach(key => {
    const value = _userMap[key];
    if (value?.label?.includes(name)) {
      list.push(Number(key));
    }
  });
  if (name && !list.length) return [0];
  return list;
};

// 申请类型级联配置
export const APPLY_PROPS = {
  emitPath: false,
  label: 'name',
  value: 'id',
  children: 'childs'
};

// 所属团队级联配置
export const TEAM_PROPS = {
  emitPath: false,
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'childs'
};

// 域名用途级联配置
export const USETO_PROPS = {
  emitPath: false,
  multiple: true,
  label: 'name',
  value: 'id',
  children: 'childs'
};

// Token状态
export const TOKEN_STATUS_LIST = [
  { label: '正常', value: true },
  { label: '无效', value: false }
];

// 使用状态
export const USE_STATUS_LIST = [
  { label: '待使用', value: 0 },
  { label: '使用中', value: 1 },
  { label: '弃用', value: 2 }
];

// 是否即将到期
export const IS_EXPIRE_BOOLEAN = [
  { label: '是', value: 1 },
  { label: '否', value: 2 }
];

// 动态筛选项
export const APPLY_CONTENT_FORM = ({ searchParams, code, field = 'code' }) => {
  return {
    domain: {
      component: 'input',
      label: '申请域名',
      placeholder: '请输入域名',
      maxlength: 100,
      // 需要显示的申请类型：投放站点申请、投放站点续费申请
      hidden() {
        return (
          searchParams[code]?.[field] !== 'domain' &&
          searchParams[code]?.[field] !== 'domain_renewal'
        );
      }
    },
    fb_account_type: {
      component: 'select',
      filterable: true,
      label: 'FB投放个号类型',
      clearable: false,
      options: [],
      // 需要显示的申请类型：FB投放个号申请
      hidden() {
        return searchParams[code]?.[field] !== 'fb_account';
      }
    },
    fb_advertisement_account_type: {
      component: 'select',
      filterable: true,
      label: 'FB广告账户',
      clearable: false,
      options: [],
      // 需要显示的申请类型：FB广告账户申请
      hidden() {
        return searchParams[code]?.[field] !== 'fb_adv_account';
      }
    },
    fb_advertisement_account: {
      component: 'input',
      label: '广告账户ID',
      placeholder: '请输入广告账户ID',
      maxlength: 100,
      // 需要显示的申请类型：FB广告账户清零申请、FB广告账户弃用申请
      hidden() {
        return (
          searchParams[code]?.[field] !== 'fb_adv_reset' &&
          searchParams[code]?.[field] !== 'fb_adv_abandon'
        );
      }
    }
  };
};
